import logging
import threading
import time
from datetime import datetime

import requests

from app.Handler.RequestHandler import RequestHandler
from app.Models.FloorVehicles import FloorVehicles
from app.Models.Model import FloorVehicle
from app.env import MES_LOGIN_URL, MES_VIN_DATA_URL, MES_VEHICLE_TIME

log = logging.getLogger('error_msg')
req = RequestHandler()


def get_token():
    """
    获取token
    """
    headers = {
        "Content-Type": "application/json"
    }
    data = {'loginName': "hzjh", 'password': "Pass@135", 'operateTerminal': 1, 'browser': "Chrome"}
    try:
        url = (
            MES_LOGIN_URL
        )  # 获取token
        response = req.visit('post', url, headers=headers, json=data)
        if response.status_code == 200:
            return response.json()["data"]["access_token"]
    except Exception as e:
        print(f"获取token请求失败，异常信息：" + str(e))
        return None


def get_data():
    """
    获取mes生产单
    """
    token = get_token()
    print('token:', token)
    headers = {
        "Authorization": token,
        "Content-Type": "application/json",
    }
    data = {"lineName": "BP05AS01"}
    try:
        response = req.visit('post', MES_VIN_DATA_URL, headers=headers, json=data)
        res_data = response.json()
        log.info("请求焊装后底板mes生产单:" + str(res_data))
        if res_data['code'] == "200":
            vehicles = FloorVehicles()
            for v in res_data['data']:
                vehicle = FloorVehicle.from_dict(v)
                vehicle.vin = vehicle.vinCode
                print(str(vehicle.to_dict()))
                vehicles.add(vehicle)
            return True
        else:
            log.error("请求焊装后底板mes生产单失败:", res_data["msg"])
            return False
    except Exception as e:
        log.error(f"根据整车物料号在SAP中获取详细物料信息请求失败，异常信息：" + str(e))


def get_mes_data():
    """
    获取mes生产单
    """
    try:
        response = requests.get('http://127.0.0.1:5200/floorVehicle/getMesOrder')
        res_data = response.json()
        if res_data['code'] == "200":
            return True
        else:
            return False
    except Exception as e:
        log.error(f"根据整车物料号在SAP中获取详细物料信息请求失败，异常信息：" + str(e))


class GetFloorMesVehicleThread(threading.Thread):
    def __init__(self):
        super(GetFloorMesVehicleThread, self).__init__()

    def run(self):
        while True:
            try:
                print("拉去Mes后底板生产序列", datetime.now().strftime('%Y-%m-%d %h:%M:%SZ'))
                get_mes_data()
                print("拉去Mes后底板生产序列完成", datetime.now().strftime('%Y-%m-%d %h:%M:%SZ'))
            except Exception as e:
                log.error('拉去Mes后底板生产序列失败, 异常：' + str(e))
            time.sleep(MES_VEHICLE_TIME)
